/**
 *    Copyright 2012 Geensoft S.A.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/
package ar.com.greensoft.neo.web.jsf.beans.user;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import org.richfaces.event.FileUploadEvent;
import org.richfaces.model.UploadedFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ar.com.greensoft.neo.dao.DaoException;
import ar.com.greensoft.neo.dao.GenericWithRevisionDao;
import ar.com.greensoft.neo.dao.ObraSocialDao;
import ar.com.greensoft.neo.model.ObraSocial;
import ar.com.greensoft.neo.search.SearchInput;
import ar.com.greensoft.neo.search.user.ObraSocialSearchInput;
import ar.com.greensoft.neo.service.ImportService;
import ar.com.greensoft.neo.util.SelectEntity;
import ar.com.greensoft.neo.web.jsf.beans.common.SearchableBean;

/**
 * @author Jorge E. Villaverde
 *
 */
@Component
@RequestScoped
@ManagedBean
public class ObraSocialBean extends UserGenericEditFacadeBean<ObraSocial> implements SearchableBean<ObraSocial>{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static final String ENTITY_PREFIX = "obraSocial";
	private static final String MENU_NAME = "menuUserObraSocial";
	
	@Autowired
	private ObraSocialDao dao;
	@Autowired
	private ImportService importService;
	
	private List<SelectEntity<ObraSocial>> importedOSList;
	
	@Override
	protected GenericWithRevisionDao<ObraSocial, Long> getDao(){
		return dao;
	}

	@Override
	protected ObraSocial newEntity() {
		ObraSocial entity = new ObraSocial();
		
		return entity;
	}

	@Override
	protected String entityPrefix() {
		return ENTITY_PREFIX;
	}

	@Override
	public String getMenuName() {
		return MENU_NAME;
	}

	@Override
	protected SearchInput createSearchInput() {
		return new ObraSocialSearchInput();
	}
	
	@Override
	protected Long getEntityId(ObraSocial t) {
		return t.getId();
	}
	
	public void processImportObraSocial(FileUploadEvent event) throws Exception {
        UploadedFile item = event.getUploadedFile();
        logger.trace("Subiendo el archivo: " + item.getName());
        
        this.importedOSList = importService.importObraSociales(item.getInputStream());
	}
	
	public List<SelectEntity<ObraSocial>> getImportedOSList() {
		return importedOSList;
	}

	public void importarObrasSociales(){
		int imported = 0;
		
		Iterator<SelectEntity<ObraSocial>> iter = importedOSList.iterator();
		
		ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
		Validator validator = factory.getValidator();

		while(iter.hasNext()){
			SelectEntity<ObraSocial> ie = iter.next();
			if(ie.isSelected()){
				iter.remove();
				try {
					Set<ConstraintViolation<ObraSocial>> constraintViolations = validator.validate(ie.getEntity());

					if(constraintViolations.size() == 0){
						dao.persist(ie.getEntity());
						imported++;
					}else{
						addErrorMessage(
								String.format("No se importa la Obra Social: %s", ie.getEntity().getSigla()));
					}
				} catch (DaoException e) {
				}
			}			
		}
				
		addInfoMessage(String.format("Se han importado %d Obras Sociales.", imported));
	}
	
	public void selectAll(ValueChangeEvent event) {
	    for(SelectEntity<ObraSocial> se : importedOSList){
	    	se.setSelected(!se.isSelected());
	    }
	    FacesContext.getCurrentInstance().renderResponse();
	}
	
	public void exportToExcel(){
		
	}
}